package com.fone.player.activity.personal;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.fone.player.R;
import com.fone.player.activity.BaseActivity;
import com.fone.player.activity.local.SortListUtil;
import com.fone.player.activity.search.adapter.OnlinePlayListAdapter;
import com.fone.player.client.Callback;
import com.fone.player.client.Error;
import com.fone.player.client.NetPlayRst;
import com.fone.player.client.NetPlayRst.Frag;
import com.fone.player.client.Request;
import com.fone.player.entity.PlayRecord;
import com.fone.player.play.FonePlayerActivity;
import com.fone.player.play.PlayerFrom;
import com.fone.player.storage.StorageModule;
import com.fone.player.util.ActivityQueue;
import com.fone.player.util.FoneUtil;
import com.fone.player.util.L;

/**
 * 
 * 网络播放
 * 
 * @author gjl
 * @since 2014-5-20
 */
public class OnlinePlayActivity extends BaseActivity implements OnClickListener {
	private String TAG = "OnlinePlayActivity";
	private EditText et_online_play_website;
	private ListView lv_online_play_history;
	private Context mContext;
	private List<PlayRecord> mHistoryVideos;
	private Button btn_back;
	private Button btn_right;
	private TextView tv_title;
	private Button btn_online_play;
	private OnlinePlayListAdapter mAdapter;
//	private List<String> urls;
	private String mWangPanUrl;
	private ArrayList<PlayRecord> recordList;
	private ProgressBar pb;
	private NetPlayCallBack callBack;
	private Handler mHandler;
	private static final int REFRUSH_DATA = 0;
	private static final int ABSOLUTE_PLAYURL_SUCCESS = 1;
	private static final int ABSOLUTE_PLAYURL_FAILURE = 2;
	private int MAX_NUM = 5;// 历史记录的最大个数

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mContext = this;
		setContentView(R.layout.online_play);
		initView();
		initHandler();
	}

	private void initHandler() {
		mHandler = new Handler() {
			@Override
			public void dispatchMessage(Message msg) {
				super.dispatchMessage(msg);
				switch (msg.what) {
				case REFRUSH_DATA:
					initData();
					break;
				case ABSOLUTE_PLAYURL_SUCCESS:
					doPlay(new String[]{(String)msg.obj}, mWangPanUrl);
					break;
				case ABSOLUTE_PLAYURL_FAILURE:
					pb.setVisibility(View.GONE);
					FoneUtil.showToast(mContext, "地址解析失败！");
					break;

				default:
					break;
				}

			}
		};
	}

	private void initView() {
		et_online_play_website = (EditText) findViewById(R.id.et_online_play_website);
		lv_online_play_history = (ListView) findViewById(R.id.lv_online_play_history);
		View online_play_title = findViewById(R.id.online_play_title);
		btn_online_play = (Button) findViewById(R.id.btn_online_play);
		btn_online_play.setOnClickListener(this);
		btn_back = (Button) online_play_title
				.findViewById(R.id.common_title_left_bt);
		btn_back.setOnClickListener(this);
		btn_right = (Button) online_play_title
				.findViewById(R.id.common_title_right_bt);
		btn_right.setVisibility(View.GONE);
		btn_back.setText("网络播放");
		tv_title = (TextView) online_play_title
				.findViewById(R.id.common_title_text_tv);
		tv_title.setVisibility(View.GONE);
		pb = (ProgressBar) findViewById(R.id.pb);
		mHistoryVideos = new ArrayList<PlayRecord>();
		mAdapter = new OnlinePlayListAdapter(mContext, mHistoryVideos);
		lv_online_play_history.setAdapter(mAdapter);
		lv_online_play_history
				.setOnItemClickListener(new OnItemClickListener() {

					@Override
					public void onItemClick(AdapterView<?> parent, View view,
							int position, long id) {
						if (FoneUtil.isNetOkWithToast(mContext)) {
							pb.setVisibility(View.VISIBLE);
							PlayRecord netPlayRecord = mHistoryVideos
									.get(position);
							mWangPanUrl = netPlayRecord.getPlayRecordName();
							L.i(TAG, "onItemClick url:" + mWangPanUrl);
							if (TextUtils.isEmpty(mWangPanUrl)) {
								FoneUtil.showToast(mContext, "地址为空！");
								return;
							}
							if (mWangPanUrl.startsWith("http://")) {
								pb.setVisibility(View.VISIBLE);
								Request.getInstance().netplay(mWangPanUrl,
										callBack);
							} else {
								String[] PlayUrls = new String[] { mWangPanUrl };
								doPlay(PlayUrls, mWangPanUrl);
							}
						}
					}
				});
//		urls = new ArrayList<String>();
	}

	private void initData() {
		callBack = new NetPlayCallBack();
		recordList = StorageModule.getInstance().getPlayRecordList(
				PlayRecord.RECORD_WEB_NETWORK);
		mHistoryVideos.clear();
		mHistoryVideos.addAll(recordList);
		SortListUtil.sortHistoryRecord(mHistoryVideos);
		limitHistoryVideos();
		mAdapter.notifyDataSetChanged();
	}

	// 限制播放记录的个数
	private void limitHistoryVideos() {

		if (mHistoryVideos != null) {
			while (mHistoryVideos.size() > MAX_NUM) {
				PlayRecord deleteRecord = mHistoryVideos.remove(mHistoryVideos
						.size() - 1);
				StorageModule.getInstance().deletePlayRecord(deleteRecord);
			}
		}
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.common_title_left_bt:
			finish();
			break;
		case R.id.btn_online_play:
			mWangPanUrl = et_online_play_website.getText().toString();
			L.i(TAG, "url:" + mWangPanUrl);
			// url="http://qd.baidupcs.com/file/a4fcf11cb3114eaed31b7225ec1e35a1?fid=1564661410-250528-686884516814820&time=1402378162&sign=FDTAXER-DCb740ccc5511e5e8fedcff06b081203-o3%2FvCK7I9OgNUdJU22LPNyEDWzM%3D&to=qb&fm=Q,B,U,nc&newver=1&expires=1402378762&rt=sh&r=712745160&logid=2009905570&sh=1&vuk=1564661410&fn=%E6%92%AD%E5%95%8A%E5%94%B1%E4%BA%A4%E6%8D%A2%E7%A9%BA%E9%97%B4%E5%BC%80%E4%BC%9A%E6%94%B6%E8%B4%B9%E6%B0%B4%E7%94%B5%E8%B4%B9%E7%AD%89%E6%96%B9%E6%B3%95.mp4";
			if (TextUtils.isEmpty(mWangPanUrl)) {
				FoneUtil.showToast(mContext, "地址为空！");
				return;
			}
			if (FoneUtil.isNetOkWithToast(this)) {
				if (mWangPanUrl.startsWith("http://")
						|| mWangPanUrl.startsWith("https://")) {

					pb.setVisibility(View.VISIBLE);
					// String url1 =
					// "http://v.youku.com/v_show/id_XNzE4Mjg3MjEy.html?from=y1.3-idx-grid-1519-9909.86808-86807.3-1";
					Request.getInstance().netplay(mWangPanUrl, callBack);
				} else {
					String[] PlayUrls = new String[] { mWangPanUrl };
					doPlay(PlayUrls, mWangPanUrl);
				}
			}

		default:
			break;
		}
	}

	/**
	 * 
	 * 
	 * @param urls
	 *            播放地址
	 * @param url
	 *            网盘地址
	 * @return void
	 * @throws
	 */
	private void doPlay(String[] urls, String url) {
		Intent intent = new Intent(this, FonePlayerActivity.class);
		intent.putExtra("from", PlayerFrom.NETWORK_PLAY);
		intent.putExtra("index", 0);
		intent.putExtra("name", url);
		intent.putExtra("urls", urls);
		startActivity(intent);
		pb.setVisibility(View.GONE);
	}

	private class NetPlayCallBack implements Callback<NetPlayRst> {

		@Override
		public void onSuccess(NetPlayRst t) {
			L.v(TAG, "NetPlayCallBack", "t : " + t.toString());
			if (t.result == 0) {
				if (t != null && t.fraglist != null) {
					List<Frag> list = t.fraglist.fragList;
					L.v(TAG, "NetPlayCallBack", "mWangPanUrl:" + mWangPanUrl);
//					urls.clear();
					String cm = t.fraglist.cm;
					final String cv = t.fraglist.cv;
					if (list != null && list.size()>0 && !TextUtils.isEmpty(cm) && !TextUtils.isEmpty(cv)) {
						
						final String url = list.get(0).url;
						if(cm.equals("use")){
							
							new Thread(){
								public void run() {
									String absolutePlayUrl = FoneUtil.getAbsolutePlayUrl(url,cv);
									L.v(TAG, "NetPlayCallBack", " absolutePlayUrl : " + absolutePlayUrl);
									if(!TextUtils.isEmpty(absolutePlayUrl)){
										mHandler.obtainMessage(ABSOLUTE_PLAYURL_SUCCESS, absolutePlayUrl).sendToTarget();
									}else{
										L.v(TAG, "NetPlayCallBack"," absolutePlayUrl is null !!! ");
										mHandler.obtainMessage(ABSOLUTE_PLAYURL_FAILURE).sendToTarget();
									}
								};
							}.start();
							return ;
						}else if(cm.equals("get")){
							L.v(TAG, "NetPlayCallBack", " cookie-method : get");
							pb.setVisibility(View.GONE);
							return;
						}
					} 
				} 
			} 
			
			L.v(TAG, "NetPlayCallBack", " response info is error !!!");
			FoneUtil.showToast(mContext, "地址解析失败！");
			pb.setVisibility(View.GONE);
		}

		@Override
		public void onFailure(Error error) {
			L.i(TAG, "error:" + error.toString());
			pb.setVisibility(View.GONE);
			if(error.isNetworkError()){
				FoneUtil.showToast(mContext, "网络超时,请稍后重试");
				return;
			}
			FoneUtil.showToast(mContext, "地址解析失败！");
		}

	}

	@Override
	protected void onResume() {
		super.onResume();
		if (ActivityQueue.popIndex(0) instanceof FonePlayerActivity) {
			mHandler.sendEmptyMessageDelayed(REFRUSH_DATA, 1000);
		} else {
			initData();
		}
	}
}
